extends Node2D

@onready var texture_rect: TextureRect = $Control/TextureRect

var dragging := false
var min_x := 0.0
var max_x := 0.0

# 关卡信息覆盖层（作为子节点叠加显示）
var level_info_scene: PackedScene = preload("res://scene/level_introduction/level1_information.tscn")
var level_info_ui: Control = null

func _ready() -> void:
	# 允许鼠标事件继续传递到未处理输入，便于在 Node2D 中处理拖拽
	texture_rect.mouse_filter = Control.MOUSE_FILTER_IGNORE
	_update_bounds()
	# 监听窗口大小变化，动态更新边界
	if get_viewport():
		get_viewport().size_changed.connect(_update_bounds)
	# 请求一次重绘，确保启动后绘制内容可见
	queue_redraw()
	# 初始化覆盖层（默认隐藏）
	_init_level_info_overlay()

func _update_bounds() -> void:
	var view_w := get_viewport().get_visible_rect().size.x
	var content_w := texture_rect.size.x
	# 如果内容宽度小于等于视口宽度，不允许移动
	if content_w <= view_w:
		min_x = 0.0
		max_x = 0.0
		texture_rect.position.x = 0.0
	else:
		# 允许在 [view_w - content_w, 0] 范围内水平移动
		min_x = view_w - content_w
		max_x = 0.0
		texture_rect.position.x = clamp(texture_rect.position.x, min_x, max_x)

	# 边界可能变化，申请重绘
	queue_redraw()

func _unhandled_input(event: InputEvent) -> void:
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
		dragging = event.pressed
		return
	if event is InputEventMouseMotion and dragging:
		var motion := event as InputEventMouseMotion
		var new_x: float = texture_rect.position.x + motion.relative.x
		texture_rect.position.x = clamp(new_x, min_x, max_x)

func _draw():
	draw_dashed_line(Vector2(0, 100), Vector2(400, 100), Color.WHITE, 2.0, 10.0, 5.0)


func _on_level_button_1_pressed() -> void:
	# 显示关卡信息层覆盖在当前页面（不切场景）
	if level_info_ui == null:
		_init_level_info_overlay()
	level_info_ui.visible = true

#
# 覆盖层初始化与交互逻辑
#
func _init_level_info_overlay() -> void:
	if level_info_ui != null:
		return
	if level_info_scene == null:
		return

	# 实例化并添加到根节点（Node2D）下，使其按视口居中/全屏显示
	level_info_ui = level_info_scene.instantiate()
	add_child(level_info_ui)

	# 使其不受父节点变换影响，按屏幕坐标定位
	level_info_ui.top_level = true
	level_info_ui.position = Vector2.ZERO

	# 充满父节点并位于最上层，阻止背景点击
	level_info_ui.anchor_left = 0.0
	level_info_ui.anchor_top = 0.0
	level_info_ui.anchor_right = 1.0
	level_info_ui.anchor_bottom = 1.0
	level_info_ui.offset_left = 0.0
	level_info_ui.offset_top = 0.0
	level_info_ui.offset_right = 0.0
	level_info_ui.offset_bottom = 0.0
	level_info_ui.z_index = 100
	level_info_ui.mouse_filter = Control.MOUSE_FILTER_STOP

	# 连接覆盖层内按钮事件
	# 按钮连接由关卡信息层自身脚本负责（避免重复连接）

	# 默认隐藏，按按钮时显示
	level_info_ui.visible = false
